/**
 * Created by Anard on 2017/4/19.
 */
let net = require('net');
let mem = require('../util/mem.js');
let call = require('../dc/call.js');
let push = require('./push.js');
let variable = require('../data/variable.js');
let msg = require('../util/msg.js');
let util = require('../util/util.js');
let log = require('../util/log.js');

let rpc = module.exports;
let link = {};

rpc.dc = function () {
    link.dc = {};
    connect('DC', 'dc', variable.dc.local, variable.dc.port, function () {
        rpc.send.dc('gateAuth', null, -1, {'serverId': util.getServerInfo('id')})
    });
};
rpc.enter = function () {
    link.enter = {};
    for (let i in variable.enter) {
        connect('登陆', 'enter', variable.enter[i].local, variable.enter[i].port);
    }
};
rpc.func = function () {
    link.func = {};
    for (let i in variable.func) {
        connect('功能', 'func', variable.func[i].local, variable.func[i].port);
    }
};
rpc.match = function () {
    link.match = {};
    for (let i in variable.match) {
        connect('排队', 'match', variable.match[i].local, variable.match[i].port);
    }
};
rpc.game = function () {
    link.game = {};
    for (let i in variable.game) {
        connect('游戏', 'game', variable.game[i].local, variable.game[i].port);
    }
};
rpc.activity = function () {
    link.activity = {};
    for (let i in variable.activity) {
        connect('活动', 'activity', variable.activity[i].local, variable.activity[i].port);
    }
};
rpc.arena = function () {
    link.arena = {};
    for (let i in variable.arena) {
        connect('比赛', 'arena', variable.arena[i].local, variable.arena[i].port);
    }
};

rpc.send = {
    dc: function (action, uuid, userId, data) {
        data = dataMix(action, uuid, data);
        msg.carry(link.dc[variable.dc.local + ':' + variable.dc.port], uuid, action, userId, data);
    },
    enter: function (action, uuid, userId, data) {
        data = dataMix(action, uuid, data);
        let port = randomPort('enter', uuid, data);
        msg.carry(port, uuid, action, userId, data);
    },
    func: function (action, uuid, userId, data) {
        data = dataMix(action, uuid, data);
        let port = randomPort('func', uuid, data);
        msg.carry(port, uuid, action, userId, data);
    },
    match: function (action, uuid, userId, data) {
        data = dataMix(action, uuid, data);
        let port = randomPort('match', uuid, data);
        msg.carry(port, uuid, action, userId, data);
    },
    game: function (action, uuid, userId, data) {
        data = dataMix(action, uuid, data);
        let port = randomPort('game', uuid, data);
        msg.carry(port, uuid, action, userId, data);
    },
    activity: function (action, uuid, userId, data) {
        data = dataMix(action, uuid, data);
        let port = randomPort('activity', uuid, data);
        msg.carry(port, uuid, action, userId, data);
    },
    arena: function (action, uuid, userId, data) {
        data = dataMix(action, uuid, data);
        let port = randomPort('arena', uuid, data);
        msg.carry(port, uuid, action, userId, data);
    },
};

function randomPort(type, uuid, data) {
    let server = null;
    if (type == 'game') {
        let gameId = null;
        if (data && data.gameId) {
            gameId = data.gameId;
        } else if (mem.clients[uuid].user && mem.clients[uuid].user.id) {
            gameId = mem.clients[uuid].user.gameId;
        }
        if (gameId) {
            server = util.getGameIdServer(gameId);
        }
    }
    if (!server) {
        if (mem.clients[uuid].user && mem.clients[uuid].user.id) {
            let len = variable[type].length;
            let key = mem.clients[uuid].user.id % len;
            server = variable[type][key];
            key = null;
            len = null;
        } else {
            server = util.getRandItemInArray(variable[type]);
        }
    }
    return link[type][server.local + ':' + server.port];
}

function connect(name, type, local, port, cb) {
    let key = local + ':' + port;
    link[type][key] = net.connect({local: local, port: port}, function () {
        log.p(name + '服务器' + key + '连接成功');
        if (cb) {
            cb();
        }
    });
    link[type][key].on("end", function () {
        log.e(name + '服务器' + key + '断开');
    });
    link[type][key].on("error", function () {
        log.e(name + '服务器' + key + '错误，尝试重连');
        setTimeout(function () {
            delete link[type][key];
            connect(name, type, local, port, cb);
        }, 1000);
    });
    link[type][key].on("data", function (message) {
        let list = util.messageToArr(message, util.getServerInfo('id'));
        foreachPush(list, type);
    });
}

function foreachPush(list) {
    for (let i in list) {
        if (!list[i]) {
            continue;
        }
        let message = list[i];
        console.log('foreachPush', util.getServerInfo('id'), message);
        push.path(message);
    }
}

function dataMix(action, uuid, data) {
    if (!data) {
        data = {};
    }
    switch (action) {
        case 'funcUserInfo':
            data.accessToken = mem.clients[uuid].user.accessToken;
            break;
        case 'funcUserFollow':
        case 'funcUserUnFollow':
            data.bluedId = mem.clients[uuid].user.bluedId;
            data.accessToken = mem.clients[uuid].user.accessToken;
            break;
        case 'funcGoods':
            data.platform = mem.clients[uuid].user.platform;
            break;
        case 'funcRecharge':
            data.accessToken = mem.clients[uuid].user.accessToken; 
            data.weixinId = mem.clients[uuid].user.weixinId;
            break;
        case 'funcGiveGift':
            data.name = mem.clients[uuid].user.name;
            data.avatar = mem.clients[uuid].user.avatar;
            break;
        case 'activitySlotMachineJoin':
            data.name = mem.clients[uuid].user.name;
            data.gold = mem.clients[uuid].user.gold;
            data.avatar = mem.clients[uuid].user.avatar;
            if (mem.clients[uuid].chip) {
                data.chip = mem.clients[uuid].chip[300001] ? mem.clients[uuid].chip[300001] : 0;
            } else {
                data.chip = 0;
            }
    }
    return data;
}